﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Windows.Media.Imaging;
using Facebook;
using Newtonsoft.Json;
using System.Collections.ObjectModel;

namespace DiscountSharing
{
    public partial class Compose : PhoneApplicationPage
    {
        private CameraCaptureTask cameraCaptureTask;
        private PhotoChooserTask photoChooserTask;
        private FacebookClient client;
        private string accessToken;
        private string albumId = null;
        private ObservableCollection<string> picUrls;
        private string albumQuery = "select object_id from album where owner=me()";

        public Compose()
        {
            InitializeComponent();
            InitAppBar();
            cameraCaptureTask = new CameraCaptureTask();
            photoChooserTask = new PhotoChooserTask();
            client = new FacebookClient();
            picUrls = new ObservableCollection<string>();
            accessToken = PhoneApplicationService.Current.State["accessToken"].ToString();

            Loaded += (o, e) =>
                {
                    DiscountMessage.Focus();
                };

            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
        }

        void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            client = new FacebookClient(accessToken);

            var picture = new FacebookMediaObject
            {
                ContentType = "image/jpeg",
                FileName = "Club Picture"
            };

            byte[] imageArray = new byte[e.ChosenPhoto.Length];
            e.ChosenPhoto.Position = 0;
            e.ChosenPhoto.Read(imageArray, 0, imageArray.Length);
            picture.SetValue(imageArray);

            client.GetCompleted += (o, args) =>
            {
                if (args.Error != null)
                {
                    return;
                }
                else
                {
                    string result = args.GetResultData().ToString();
                    AlbumPage albumPage = JsonConvert.DeserializeObject<AlbumPage>(result);
                    if (albumPage.data.Length == 0)
                    {
                        //no dealspatrol album
                        client.PostAsync("me/albums", new { name = "dealspatrol" });
                        albumId = null;
                    }
                    else
                    {
                        //album named dealspatrol exists
                        albumId = albumPage.data[0].object_id;
                        client.PostAsync(String.Format("{0}/photos", albumId), new { source = picture, message = "via dealspatrol" });
                        Dispatcher.BeginInvoke(() => ApplicationBar.IsMenuEnabled = false);
                    }
                }
            };

            client.PostCompleted += (o, args) =>
                {
                    if (args.Error != null)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to attach!"));
                    }
                    else
                    {
                        if (albumId == null)
                        {
                            client.GetAsync("fql", new { q = albumQuery });
                        }
                        else
                        {
                            string result = args.GetResultData().ToString();
                            UploadedPicture pic = JsonConvert.DeserializeObject<UploadedPicture>(result);
                            picUrls.Add(String.Format("http://www.facebook.com/photo.php?fbid={0}", pic.id));
                            Dispatcher.BeginInvoke(() => 
                            {
                                MessageBox.Show("Picture attached!");
                                BitmapImage bi = new BitmapImage();
                                bi.SetSource(e.ChosenPhoto);
                                DiscountPic.Source = bi;
                                ApplicationBar.IsMenuEnabled = true;
                            });
                        }
                    }
                };

            client.GetAsync("fql", new { q = albumQuery });
        }

        private void InitAppBar()
        {
            ApplicationBarIconButton cameraButton = new ApplicationBarIconButton(new Uri("/Images/MenuIcon/appbar.feature.camera.rest.png", UriKind.Relative));
            cameraButton.Text = "camera";
            cameraButton.Click += (o, e) =>
            {
                try
                {
                    cameraCaptureTask.Show();
                }
                catch
                {
                    MessageBox.Show("Error: fail to launch camera...");
                }
            };

            ApplicationBarIconButton uploadButton = new ApplicationBarIconButton(new Uri("/Images/MenuIcon/appbar.upload.rest.png", UriKind.Relative));
            uploadButton.Text = "submit";
            uploadButton.Click += (o, e) =>
            {
                client = new FacebookClient(accessToken);
                string[] messages = DiscountMessage.Message.Split('@');

                client.PostCompleted += (obj, args) =>
                {
                    if (args.Error != null)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show("Failed to upload!"));
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("Uploaded!");
                                NavigationService.GoBack();
                            });
                    }
                };

                client.PostAsync("me/feed", new {
                    message = String.Format("{0}@{1}:{2}", messages[0], DiscountCategory.SelectedCategory, messages[1])
                    + (picUrls.Count > 0 ? String.Format("\nImage Attached:{0}", picUrls[0]) : String.Empty)
                });
            };

            ApplicationBar.Buttons.Add(cameraButton);
            ApplicationBar.Buttons.Add(uploadButton);
        }

        public class Album
        {
            public string object_id;
        }

        public class AlbumPage
        {
            public Album[] data;
        }

        public class UploadedPicture
        {
            public string id;
        }
    }
}